<template>
  <ContentWrap>
    <div v-loading="formLoading" :style="`height:${contentHeight}px`">
      <div class="routeHeader" v-loading="formLoading">
        <el-button
          class="mr-5px"
          type="primary"
          @click="saveForm"
          v-if="!detailStatus"
          v-loading="formLoading"
          >保 存</el-button
        >
        <el-button type="primary" @click="sumbit" v-if="!detailStatus" v-loading="formLoading"
          >提交</el-button
        >
        <el-button @click="goBack" v-loading="formLoading">关闭</el-button>
      </div>
      <el-table
        ref="multipleTableRef"
        :data="list"
        border
        style="width: 100%"
        class="tableView"
        v-loading="formLoading"
        :height="contentHeight - 60"
      >
        <el-table-column label="序号" align="center" type="index" :min-width="80" />
        <el-table-column
          label="工单号/任务单号"
          align="left"
          header-align="left"
          prop="workTaskNumber"
          :min-width="150"
        />
        <el-table-column
          label="产品编号"
          align="left"
          header-align="left"
          prop="productNumber"
          :min-width="150"
        />
        <el-table-column
          label="产品名称"
          align="left"
          header-align="left"
          prop="productName"
          :min-width="120"
        />
        <el-table-column
          label="产品规格"
          align="left"
          header-align="left"
          prop="productStandard"
          :min-width="120"
        />
        <el-table-column
          label="订单数量"
          align="left"
          header-align="left"
          prop="orderQuantity"
          :min-width="120"
        />
        <el-table-column
          label="编号"
          align="left"
          header-align="left"
          prop="serialNumber"
          :min-width="120"
        />
        <el-table-column
          label="部件编号"
          align="left"
          header-align="left"
          prop="partNumber"
          :min-width="120"
        />
        <el-table-column
          label="部件名称"
          align="left"
          header-align="left"
          prop="partName"
          :min-width="120"
        />
        <el-table-column
          label="图纸图号"
          align="left"
          header-align="left"
          prop="partDrawingNumber"
          :min-width="150"
        >
          <template #default="scope">
            <el-button
              class="drawingBtn"
              type="primary"
              link
              @click="jumpPdfFile(scope.row.partDrawingNumber)"
              >{{ scope.row.partDrawingNumber }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column
          label="部件规格"
          align="left"
          header-align="left"
          prop="partSpecification"
          :min-width="120"
        />
        <el-table-column
          label="材质"
          align="left"
          header-align="left"
          prop="material"
          :min-width="120"
        />
        <el-table-column
          label="规格"
          align="left"
          header-align="left"
          prop="productStandard"
          :min-width="120"
        />
        <el-table-column
          label="净尺寸（长）"
          align="left"
          header-align="left"
          prop="netSizeLength"
          :min-width="120"
        />
        <el-table-column
          label="净尺寸（宽）"
          align="left"
          header-align="left"
          prop="netSizeWidth"
          :min-width="120"
        />
        <el-table-column
          label="下料尺寸（长）"
          align="left"
          header-align="left"
          prop="cuttingSizeLength"
          :min-width="130"
        />
        <el-table-column
          label="下料尺寸（宽）"
          align="left"
          header-align="left"
          prop="cuttingSizeWidth"
          :min-width="130"
        />
        <el-table-column
          label="计划数量"
          align="left"
          header-align="left"
          prop="planQuantity"
          :min-width="100"
        />
        <el-table-column
          label="工序名称"
          align="left"
          header-align="left"
          prop="dictProcessName"
          :min-width="120"
        >
          <template #default="scope">
            <byte-tag
              className="test"
              :type="'craft_process_name'"
              :value="scope.row.dictProcessName"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="下料工序"
          aalign="left"
          header-align="left"
          prop="dictTypeOfWork"
          :min-width="120"
        >
          <template #default="scope">
            <byte-tag
              className="test"
              :type="'config_manufacturing_details_cutting_process'"
              :value="scope.row.dictTypeOfWork"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="下料类型"
          align="left"
          header-align="left"
          prop="dictBaitingType"
          :min-width="120"
        >
          <template #default="scope">
            <byte-tag
              className="test"
              :type="'config_wage_baiting_type'"
              :value="scope.row.dictBaitingType"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="是否机加"
          align="left"
          header-align="left"
          prop="dictIsMachine"
          :min-width="80"
        >
          <template #default="scope">
            <byte-tag className="test" :type="'is_machining'" :value="scope.row.dictIsMachine" />
          </template>
        </el-table-column>
        <el-table-column
          label="机加工序"
          align="left"
          header-align="left"
          prop="dictMachiningProcess"
          :min-width="80"
        >
          <template #default="scope">
            <byte-tag
              className="test"
              :type="'machining_process'"
              :value="scope.row.dictMachiningProcess"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="生产班组"
          align="left"
          header-align="left"
          prop="productionTeam"
          :min-width="150"
        >
          <template #default="scope">
            <el-select
              v-model="scope.row.productionTeam"
              placeholder="请选择"
              filterable
              clearable
              class="!w-120px"
              :disabled="detailStatus || scope.row.dictProductiveTaskStatus === 30"
            >
              <el-option
                v-for="dict in OrgTeamArchivesList"
                :key="dict.id"
                :label="dict.teamName"
                :value="dict.teamName"
              />
            </el-select>
          </template>
        </el-table-column>
        <!--  -->
        <el-table-column
          label="设备名称"
          align="left"
          header-align="left"
          prop="deviceName"
          :min-width="150"
        >
          <template #default="scope">
            <el-select
              v-model="scope.row.deviceName"
              placeholder="请选择"
              filterable
              clearable
              class="!w-120px"
              :disabled="detailStatus || scope.row.dictProductiveTaskStatus === 30"
              @change="
                (val) => {
                  selectDeviceName(val, scope.$index, scope, 'deviceName')
                }
              "
            >
              <el-option
                v-for="dict in deviceList"
                :key="dict.id"
                :label="dict.deviceName"
                :value="dict.deviceName"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          label="设备编码"
          align="left"
          header-align="left"
          prop="deviceCode"
          :min-width="150"
        >
          <template #default="scope">
            <el-select
              v-model="scope.row.deviceCode"
              placeholder="请选择"
              filterable
              clearable
              :disabled="detailStatus || scope.row.dictProductiveTaskStatus === 30"
              class="!w-120px"
              @change="(val)=>{selectDeviceCode(val,scope.$index,scope,'deviceCode')}"
            >
              <el-option
                v-for="dict in deviceList"
                :key="dict.id"
                :label="dict.deviceCode"
                :value="dict.deviceCode"
              />
            </el-select>
          </template>
        </el-table-column>
        <!-- -->
        <el-table-column
          label="作业者"
          align="left"
          header-align="left"
          prop="operator"
          :min-width="150"
          class="m-4"
        >
          <template #default="scope">
            <el-input
              class="fontHide"
              readonly
              v-model="scope.row.operator"
              @click="openOperator(scope.row.jobNumber, scope.$index, scope)"
              :disabled="detailStatus || scope.row.dictProductiveTaskStatus === 30"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="计划开始日期"
          align="left"
          header-align="left"
          prop="planStartDate"
          :min-width="220"
        >
          <template #default="scope">
            <el-date-picker
              style="width: 180px"
              v-model="scope.row.planStartDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="选择计划开始日期"
              :disabled="detailStatus || scope.row.dictProductiveTaskStatus === 30"
             
            />
          </template>
        </el-table-column>
        <!-- @change="change(scope, 'planStartDate')" -->
        <el-table-column
          label="计划结束日期"
          align="left"
          header-align="left"
          prop="planEndDate"
          :min-width="220"
        >
          <template #default="scope">
            <el-date-picker
              style="width: 180px"
              v-model="scope.row.planEndDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="选择计划结束时间"
              :disabled="detailStatus || scope.row.dictProductiveTaskStatus === 30"
              
            />
          </template>
        </el-table-column>
        <!-- @change="change(scope, 'planEndDate')" -->
        <el-table-column
          label="位置"
          align="left"
          header-align="left"
          prop="warehousePosition"
          :min-width="150"
        >
          <template #default="scope">
            <el-select
              v-model="scope.row.warehousePosition"
              placeholder="请选择"
              filterable
              clearable
              :disabled="detailStatus || scope.row.dictProductiveTaskStatus === 30"
              class="!w-120]px"
              
            >
              <el-option
                v-for="dict in warehousePositionList"
                :key="dict.id"
                :label="dict.warehousePosition"
                :value="dict.warehousePosition"
              />
            </el-select>
          </template>
        </el-table-column>
        <!-- @change="change(scope, 'warehousePosition')" -->
        <el-table-column
          label="状态"
          align="left"
          header-align="left"
          prop="dictProductiveTaskStatus"
          :min-width="80"
        >
          <template #default="scope">
            <byte-tag
              className="test"
              :type="'productive_task_status'"
              :value="scope.row.dictProductiveTaskStatus"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" header-align="left">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="delRow(scope.$index)"
              v-hasPermi="['produce:production-task-order:delRow']"
              v-if="!detailStatus && scope.row.dictProductiveTaskStatus !== 30"
            >
              移除行
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </ContentWrap>
  <!-- 作业者 -->
  <operator ref="operatorRef" @setOperator="setOperator" />
</template>
<script setup>
  import { jumpPdfFile } from '@/utils/formCreate'
  import * as ProductionTaskOrderApi from '@/api/produce/workOrderManagement/productionTaskOrder'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import ByteTag from './ByteTag.vue'
  import operator from './operator.vue'
  const message = useMessage() // 消息弹窗
  const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
  const { t } = useI18n() // 国际化
  const { query } = useRoute() // 路由的查询
  const list = ref([]) //渲染数据

  //选中第一行自动填充其余行
  //  const change = (scope,val) =>{
  //    if(!scope.$index){
  //      if(scope.row[val]){
  //        for(let i=1;i<=list.value.length-1;i++){
  //          for(let k in list.value[i]){
  //            if(k==val){
  //              list.value[i][val] = scope.row[val]
  //            }
  //          }
  //        }
  //      }
  //    }
  //  }
  // 提交
  const sumbit = async () => {
    let sumbitBol = ref(true)
    list.value.forEach((item) => {
      if (!item.operator) {
        sumbitBol.value = false
        message.error(t('作业者不能为空'))
        return false
      }
    })
    list.value.forEach((item) => {
      if (item.dictProcessName === 10 || item.dictProcessName === 20) {
        if (!item.deviceName || !item.deviceCode) {
          sumbitBol.value = false
          message.error(t('设备名称/设备编码不能为空'))
          return false
        }
      }
      if (
        !item.productionTeam ||
        !item.planStartDate ||
        !item.planEndDate ||
        !item.warehousePosition
      ) {
        sumbitBol.value = false
        message.error(t('生产班组/计划开始时间/计划结束时间/位置不能为空'))
        return false
      }
    })
    let data = JSON.parse(JSON.stringify(list.value))
    for (let i = 0; i < data.length; i++) {
      if (data[i].productionTeam == '同上') {
        data[i].productionTeam = data[i - 1].productionTeam
      }
      if (data[i].deviceName == '同上') {
        data[i].deviceName = data[i - 1].deviceName
      }
      if (data[i].deviceCode == '同上') {
        data[i].deviceCode = data[i - 1].deviceCode
      }
      if (data[i].operator == '同上') {
        data[i].operator = data[i - 1].operator
        data[i].jobNumber = data[i - 1].jobNumber
      }
      if (data[i].warehousePosition == '同上') {
        data[i].warehousePosition = data[i - 1].warehousePosition
      }
    }
    //计划结束日期不能早于计划开始日期
    for (let i = 0; i < data.length; i++) {
      const event = data[i]
      if (event.planEndDate < event.planStartDate) {
        message.error('计划结束日期不能早于计划开始日期')
        formLoading.value = false
        return
      }
    }
    let reqData = {
      submitFlag: 1,
      updateList: data
    }
    if (sumbitBol.value) {
      console.log(reqData)
      await ProductionTaskOrderApi.putProductionTaskOrderList(reqData)
      message.success(t('提交成功'))
      goBack()
    }
  }

  // 获取生产班组
  const OrgTeamArchivesList = ref([])
  const getOrgTeamArchives = async () => {
    OrgTeamArchivesList.value = await ProductionTaskOrderApi.getOrgTeamArchives()
  }

  // 获取设备名称
  const deviceList = ref([])
  const getDeviceMessageList = async () => {
    deviceList.value = await ProductionTaskOrderApi.getDeviceMessageList()
  }

  const selectDeviceName = async (val, index, scope, name) => {
    if (!scope.$index) {
      if (scope.row[name]) {
        // for (let i = 1; i <= list.value.length - 1; i++) {
        //   for (let k in list.value[i]) {
        //     if (k == name) {
        //       list.value[i][name] = scope.row[name]
        //     }
        //   }
        // }
        // deviceList.value.forEach((item) => {
        //   if (item.deviceName == val) {
        //     for (let i = 1; i <= list.value.length - 1; i++) {
        //       list.value[i].deviceCode = item.deviceCode
        //     }
        //   }
        // })
      }
    }

    if (!val) {
      list.value[index].deviceCode = ''
    } else {
      list.value[index].deviceCode = ''
      deviceList.value.forEach((item) => {
        if (item.deviceName == val) {
          list.value[index].deviceCode = item.deviceCode
        }
      })
    }
  }

  const selectDeviceCode = async (val, index, scope, name) => {
    if (!scope.$index) {
      if (scope.row[name]) {
        // for (let i = 1; i <= list.value.length - 1; i++) {
        //   for (let k in list.value[i]) {
        //     if (k == name) {
        //       list.value[i][name] = scope.row[name]
        //     }
        //   }
        // }
        // deviceList.value.forEach((item) => {
        //   if (item.deviceCode == val) {
        //     for (let i = 1; i <= list.value.length - 1; i++) {
        //       list.value[i].deviceName = item.deviceName
        //     }
        //   }
        // })
      }
    }
    if (!val) {
      list.value[index].deviceName = ''
    } else {
      list.value[index].deviceName = ''
      deviceList.value.forEach((item) => {
        if (item.deviceCode == val) {
          list.value[index].deviceName = item.deviceName
        }
      })
    }
  }

  // 获取作业者
  const operatorRef = ref()
  const openOperator = (jobNumberStr, index) => {
    const jobNumberList = null
    if (jobNumberList != null) {
      jobNumberList = jobNumberStr.split(',')
    }
    operatorRef.value.open(jobNumberList, index)
  }

  // 设置作业者
  const setOperator = (index) => {
    const operator = operatorRef.value.multipleSelection
    const operatorNumber = []
    const operatorName = []
    operator.forEach((item) => {
      operatorNumber.push(item.jobNumber)
      operatorName.push(item['staffName'])
    })
    // if (index < 1) {
    //   for (let i = 1; i <= list.value.length - 1; i++) {
    //     for (let k in list.value[i]) {
    //       if (k == 'operator') {
    //         list.value[i].jobNumber = operatorNumber.join(',')
    //         list.value[i].operator = operatorName.join(',')
    //       }
    //     }
    //   }
    // }
    list.value[index].jobNumber = operatorNumber.join(',')

    list.value[index].operator = operatorName.join(',')
  }

  // 获取位置
  const warehousePositionList = ref([])
  const warehousePosition = async () => {
    warehousePositionList.value = await ProductionTaskOrderApi.getWarehousePosition()
  }

  /**关闭*/
  const tagsViewStore = useTagsViewStore()
  const route = useRouter() // 路由
  const goBack = async () => {
    //获取当前路由并删除tagView
    tagsViewStore.delView(route.currentRoute.value)
    //跳转列表页
    route.push({
      path: '/produce/produce/workOrderManagement/productionTaskOrder'
    })
  }

  //删除行
  const delRow = (index) => {
    list.value.splice(index, 1)
  }

  /** 保存 */
  const saveForm = async () => {
    let saveBol = ref(true)
    list.value.forEach((item) => {
      if (!item.operator) {
        message.error(t('作业者不能为空'))
        return false
      }
    })
    list.value.forEach((item) => {
      if (item.dictProcessName === 10 || item.dictProcessName === 20) {
        if (!item.deviceName || !item.deviceCode) {
          saveBol.value = false
          message.error(t('设备名称/设备编码不能为空'))
          return false
        }
      }
      if (
        !item.productionTeam ||
        !item.planStartDate ||
        !item.planEndDate ||
        !item.warehousePosition
      ) {
        saveBol.value = false
        message.error(t('生产班组/计划开始时间/计划结束时间/位置不能为空'))
        return false
      }
    })
    formLoading.value = true
    let data = JSON.parse(JSON.stringify(list.value))
    for (let i = 0; i < data.length; i++) {
      if (data[i].productionTeam == '同上') {
        data[i].productionTeam = data[i - 1].productionTeam
      }
      if (data[i].deviceName == '同上') {
        data[i].deviceName = data[i - 1].deviceName
      }
      if (data[i].deviceCode == '同上') {
        data[i].deviceCode = data[i - 1].deviceCode
      }
      if (data[i].operator == '同上') {
        data[i].operator = data[i - 1].operator
      }
      if (data[i].warehousePosition == '同上') {
        data[i].warehousePosition = data[i - 1].warehousePosition
      }
    }
    //计划结束日期不能早于计划开始日期
    for (let i = 0; i < data.length; i++) {
      const event = data[i]
      if (event.planEndDate < event.planStartDate) {
        message.error('计划结束日期不能早于计划开始日期')
        formLoading.value = false
        return
      }
    }
    let reqData = {
      submitFlag: 1,
      updateList: data
    }
    if (saveBol.value) {
      await ProductionTaskOrderApi.putSave(reqData)
      message.success(t('保存成功'))
      goBack()
    }
    formLoading.value = false
  }

  const temp = ref()
  const detailStatus = ref(false) //查看状态
  const contentHeight = ref(0)
  /** 初始化 */
  onMounted(async () => {
    contentHeight.value = document.body.clientHeight - 150
    if (query.type == 'work' || query.type == 'details') {
      if (query.type == 'details') {
        detailStatus.value = true
      }
      formLoading.value = true
      temp.value = await ProductionTaskOrderApi.getProductionTaskOrder(query.id)
      // 接收到的是对象要加进数组里才能渲染
      list.value.push(temp.value)
      formLoading.value = false
    } else if (query.type == 'works') {
      formLoading.value = true
      let data = await ProductionTaskOrderApi.getProductionTaskOrderList(JSON.parse(query.id))
      for (let i = 1; i < data.length; i++) {
        data[i].productionTeam = '同上'
        data[i].deviceName = '同上'
        data[i].deviceCode = '同上'
        data[i].operator = '同上'
        data[i].warehousePosition = '同上'
      }
      list.value = data
      formLoading.value = false
    }
    console.log(list.value)
    getOrgTeamArchives()
    getDeviceMessageList()
    warehousePosition()
    // 获取设备编码、作业者下拉信息
    // list.value.forEach( async (item,i)=>{
    //   //设备编码
    //    deviceCodeList.value[i] = await ProductionTaskOrderApi.getDeviceMessageList({deviceName:item.deviceName})
    // })
  })
</script>
<style lang='scss' scoped >
  .tableView {
    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
      cursor: default;
      .el-input__inner {
        cursor: default !important;
        text-align: center;
      }
    }
  }
  .fontHide {
    width: 100%;
    height: 100%;
    white-space: nowrap;
    text-overflow: clip;
    overflow: hidden;
  }
  .drawingBtn {
    white-space: normal;
    word-wrap: break-word;
    overflow-wrap: break-word;
  }
</style>